﻿using Surging.Core.CPlatform.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Surging.Core.CPlatform.Filters.Implementation
{
    public class DoraAuthorizationAttribute : AuthorizationAttribute
    {
        /// <summary>
        /// 验证方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override bool OnAuthorization(ServiceRouteContext context)
        {
            // 
            var id = context.Route.ServiceDescriptor.Id;
            var path = context.Route.ServiceDescriptor.RoutePath;
            if (AukeyList == null)
            {
                return true;
            }
            else {
                foreach (var key in AukeyList)
                {
                    //和redis比对  

                }

            }

            return true;
        }


        /// <summary>
        /// 权限的集合字符串，用,隔开
        /// </summary>
        public string AuthKey { get; set; }
        private List<string> _authKeyList { get; set; }
        /// <summary>
        /// 权限key集合
        /// </summary>
        public List<string> AukeyList
        {
            get
            {
                if (string.IsNullOrWhiteSpace(AuthKey))
                    return null;
                string[] keyArray;
                try
                {
                    keyArray = AuthKey.Split(',');
                }
                catch
                {
                    //log一下
                    return null;
                }
                return keyArray != null && keyArray.Length > 0 ? keyArray.ToList() : null;
            }
        }

        /// <summary>
        /// 验证过程以及结果
        /// </summary>
        /// <param name="serviceRouteContext"></param>
        /// <param name="cancellationToken"></param>
        public override void ExecuteAuthorizationFilterAsync(ServiceRouteContext serviceRouteContext, CancellationToken cancellationToken)
        {
            var result = OnAuthorization(serviceRouteContext);
            if (!result)
            {
                serviceRouteContext.ResultMessage.StatusCode = 401;
                serviceRouteContext.ResultMessage.ExceptionMessage = "令牌验证失败.";
            }
        }

    }
}
